// Copyright (c) 2025, 大连理工大学 (Dalian University of Technology)
//
// Licensed under the Mulan PSL v2.
// You can use this file according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of the License at
//
//     http://license.coscl.org.cn/MulanPSL2
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. SEE THE MULAN PSL v2
// FOR MORE DETAILS.

#include "DBManager/Repository/HDF5/Input/Constraint/MPCRepository.h"

#include "DBManager/Repository/HDF5/Base/HDF5RepositoryMacro.h"

HDF5_REG_REPOSITORY (MPCRepository)

using namespace SG::DBManager::HDF5;
using namespace SG::DBManager::HDF5::MPC;
using namespace SG::DataStructure::Common;
using namespace SG::DataStructure::FEM;

// 构造函数实现
MPCRepository::MPCRepository (HDF5Database& database) : SG::DBManager::HDF5::SetRepositoryBase<SG::DataStructure::FEM::MPCData> (database)
{}

void MPCRepository::InitialDatasetInfo ()
{
    RegisterTableInfo<IDENTITY> ("/SG/INPUT/CONSTRAINT/MPC/IDENTITY", MainDataset);
    RegisterIndex ("/OWN/INDEX/INPUT/CONSTRAINT/MPC", IndexDataset, GetType ());
    RegisterTableInfo<MPCData::MPCComponent> ("/SG/INPUT/CONSTRAINT/MPC/GCA", SubDataset);

    // 连接信号槽 当调用汇总的时候，将已有的缓存信息全部都持久化到HDF5文件中。
    GetDatabase ().GetHDF5Hub()->m_constraintSummarySignal.connect ([this] { Sort (); });
}

void MPCRepository::DumpWriteCahce ()
{
    auto& writeStorage = this->GetMainCache ().m_writeStorage;

    // 1. flag设置为无顺序
    GetMainDatasetInfo ().SetIsSequential (false);

    // 主表数据
    std::vector<IDENTITY> IDENTITYData{};
    // 附表数据
    std::vector<MPCData::MPCComponent> subData;

    // 2. 转换为nastran格式数据
    OwnToNastran (writeStorage, IDENTITYData, subData);

    // 3. 写出数据至文件
    WriteData (MainDataset, IDENTITYData);
    WriteData (SubDataset, subData);

    // 4. 更新Index表
    this->WriteIndexData (this->GetIndexDatasetInfo (), writeStorage);

    // 5. 清空缓存
    writeStorage.clear ();
}

std::vector<MPCRepository::DataType>* MPCRepository::LoadReadCache (std::size_t loadIndex)
{
    // 1. 读取范围内主表数据
    std::vector<IDENTITY> IDENTITYData;
    LoadMainMetadata (loadIndex, IDENTITYData);

    if (IDENTITYData.empty ())
    {
        return nullptr;
    }

    // 2. 读取范围内附表数据
    std::vector<MPCData::MPCComponent> subData;
    LoadSecondaryMetadata (IDENTITYData, GCA_POS, GCA_LEN, SubDataset, subData);

    // 3. 将数据转换为自己的格式放入缓存
    auto* cacheVector = m_cacheHelper.LookupOrCreateVector<DataType> (GetMainCache ().m_readCacheKey, IDENTITYData.size ());
    NastranToOwn (IDENTITYData, subData, *cacheVector);
    return cacheVector;
}

void MPCRepository::SortData ()
{
    // 1. 读取主表数据
    std::vector<IDENTITY> IDENTITYData;
    GetDataset (MainDataset).read (IDENTITYData);

    if (IDENTITYData.empty ())
    {
        GetMainDatasetInfo ().SetIsSequential (true);
        return;
    }

    // 2. 读取附表数据
    std::vector<MPCData::MPCComponent> subData;
    GetDataset (SubDataset).read (subData);

    // 3. 将所有数据转换
    std::vector<MPCData> AllData{};
    NastranToOwn (IDENTITYData, subData, AllData);

    // 4. 排序
    std::sort (AllData.begin (), AllData.end ());

    // 5. 转换回nastran格式
    OwnToNastran (AllData, IDENTITYData, subData, true);

    // 6. 写出主表数据至文件
    GetDataset (MainDataset).write (IDENTITYData);
    // 7. 写出附表数据至文件
    GetDataset (SubDataset).write (subData);

    // 8. 重写索引
    RewriteIndexData (AllData);

    // 9. 设置为已顺序
    GetMainDatasetInfo ().SetIsSequential (true);
}

SG::DataStructure::Common::Status MPCRepository::FindBySId (SG::DataStructure::Common::Id                      sId,
                                                            std::vector<SG::DataStructure::FEM::MPCData>& _OUT arrs)
{
    // 1. 确定数据是排序过的
    this->Sort ();

    // 2. 读取主表数据
    std::vector<IDENTITY> IDENTITYData;
    if (FindMainRangeBySId (sId, IDENTITYData) == SG::DataStructure::Common::Status::STATUS_Success)
    {
        // 3. 查询副表数据
        std::vector<MPCData::MPCComponent> subData;
        LoadSecondaryMetadata (IDENTITYData, GCA_POS, GCA_LEN, SubDataset, subData);

        // 4. 转换数据
        NastranToOwn (IDENTITYData, subData, arrs);

        return SG::DataStructure::Common::Status::STATUS_Success;
    }
    return SG::DataStructure::Common::Status::STATUS_Failure;
}

void MPCRepository::OwnToNastran (std::vector<MPCData>&                    own,
                                  std::vector<IDENTITY>& _OUT              IDENTITYData,
                                  std::vector<MPCData::MPCComponent>& _OUT subData,
                                  bool                                     isSort)
{
    subData.clear ();
    IDENTITYData.clear ();
    IDENTITYData.reserve (own.size ());

    // 获取已有数据条数，主要是放在主表的POS字段
    // 如果是重新排序的时候，Pos都是从0 开始的
    size_t count = isSort ? 0 : this->GetDatasetInfo (SubDataset).GetRowCount ();

    // OwnIdent 代表咱们自己的数据结构
    // NasIdent 代表nastran的数据结构
    for (auto& OwnIdent : own)
    {
        // 写入附表
        subData.insert (subData.end (), OwnIdent.m_masterItems.begin (), OwnIdent.m_masterItems.end ());

        const size_t len = OwnIdent.m_masterItems.size ();

        // 写入IDENTITY 双表的主要这里编写一下
        IDENTITY NasIdent{};
        NasIdent.SID       = OwnIdent.m_sId;
        NasIdent.G         = OwnIdent.m_slaveItem.m_nodeId;
        NasIdent.C         = OwnIdent.m_slaveItem.m_dof;
        NasIdent.A         = OwnIdent.m_slaveItem.m_factor;
        NasIdent.GCA_POS   = static_cast<SG::DataStructure::Common::I64> (count);
        NasIdent.GCA_LEN   = static_cast<SG::DataStructure::Common::I64> (len);
        NasIdent.DOMAIN_ID = OwnIdent.m_domainId;

        IDENTITYData.emplace_back (NasIdent);

        count += len;
    }
}

void MPCRepository::NastranToOwn (std::vector<IDENTITY>&              IDENTITYData,
                                  std::vector<MPCData::MPCComponent>& subData,
                                  std::vector<MPCData>& _OUT          own)
{
    own.clear ();
    own.reserve (IDENTITYData.size ());

    // 代表初始的Index 位置, 因为数据有可能是截取了附表的一部分，所有主表中根据POS找的时候需要对应一下，
    // 比如第一个主表数据中POS字段为10000， 附表的vector的数据 就是从附表中的第10000个开始对应的 也就是Index==0的
    const SG::DataStructure::Common::I64 index = IDENTITYData[0].GCA_POS;

    MPCData const tempown;
    own.resize (IDENTITYData.size (), tempown);

    for (size_t i = 0; i < IDENTITYData.size (); i++)
    {
        auto& OwnIdent = own[i];
        auto& NasIdent = IDENTITYData[i];

        OwnIdent.m_sId                = NasIdent.SID;
        OwnIdent.m_slaveItem.m_nodeId = NasIdent.G;
        OwnIdent.m_slaveItem.m_dof    = NasIdent.C;
        OwnIdent.m_slaveItem.m_factor = NasIdent.A;
        OwnIdent.m_domainId           = NasIdent.DOMAIN_ID;

        if (NasIdent.GCA_LEN != 0)
        {
            OwnIdent.m_masterItems.assign (subData.begin () + NasIdent.GCA_POS - index,
                                           subData.begin () + NasIdent.GCA_POS + NasIdent.GCA_LEN - index);
        }
    }
}
